package com.leo.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

public enum InnerObjectUtile{
	SESSION(ServletActionContext.SESSION),
	COOKIES("cookie"),
	REQUEST("request"),
	RESPONSE("response");
	String orgName = null;
	InnerObjectUtile(String orgName){
		this.orgName = orgName;
	}
	
	static public void removeSession(){
		HttpSession session = null;
		if( (session = ServletActionContext.getRequest().getSession(false)) == null)
			return;
		session.setMaxInactiveInterval(0);
	}
	
	public Map<String,String> getMap(){
		if(this.orgName.equals(COOKIES)){
			return new MyCookie();
		}
		else
			return  (Map<String,String>) ActionContext.getContext().get(this.orgName);
	}
	
	class MyCookie extends HashMap<String,String>{
		
		//private Cookie[] cookies;

		public MyCookie(){
			Cookie[] cookies = ServletActionContext.getRequest().getCookies();
			for(Cookie ck: cookies){
				super.put(ck.getName(), ck.getValue());
			}
		}
		
		@Override
		public String put(String key, String value) {
			// TODO Auto-generated method stub
			ServletActionContext.getResponse().addCookie(new Cookie(key,value));
			return super.put(key, value);
		}

		@Override
		public String remove(Object key) {
			// TODO Auto-generated method stub
			Cookie cookie = new Cookie(key.toString(), "");
			ServletActionContext.getResponse().addCookie(cookie);
			return super.remove(key);
		}
		
		@Override
		public void putAll(Map<? extends String, ? extends String> m) {
			// TODO Auto-generated method stub
			Set<? extends String> keys = m.keySet();
			HttpServletResponse respone = ServletActionContext.getResponse();
			for (String key : keys) {
				respone.addCookie(new Cookie(key,m.get(key)));
			}
			super.putAll(m);
		}
		
		@Override
		public void clear() {
			// TODO Auto-generated method stub
			Set<? extends String> keys = super.keySet();
			HttpServletResponse respone = ServletActionContext.getResponse();
			for (String key : keys) {
				Cookie cookie = new Cookie(key,"");
				cookie.setMaxAge(0);
				respone.addCookie(cookie);
			}
			super.clear();
		}
	}
}